<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/taglibs.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>撰写新文章</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />

<!-- BEGIN PAGE LEVEL PLUGINS -->
 
<!-- END PAGE LEVEL PLUGINS -->


<!-- blog css -->

<link rel="stylesheet" href="${ctx}/resources/blog/css/normalize.css">
<link rel="stylesheet" href="${ctx}/resources/blog/css/grid.css">
<link rel="stylesheet" href="${ctx}/resources/blog/css/style.css">

<!-- end blog css -->
<style>
.page-content {
	margin-left: 0 !important;
	background-color: #f5f5f5 !important;
}

#pages {
	padding: 0;
	text-align: right
}

#pages a, #pages span {
	display: inline-block;
	height: 28px;
	line-height: 28px;
	background: #fff;
	border: 1px solid #e3e3e3;
	text-align: center;
	color: #333;
	padding: 0 15px;
	margin-left: 1px;
}

 

#pages a:hover {
	background: #f1f1f1;
	color: #000;
	text-decoration: none;
}

#pages span {
	background: #368ee0;
	color: #fff;
}
</style>
<script type="text/javascript">
	var ctx = "${ctx}";
</script>
</head>
<body class="page-content-white page-footer-fixed" index="nheader"
	style="background-color: #f5f5f5;">


	<!-- BEGIN CONTAINER -->
	<div class="page-container" style="margin-bottom: 0px !important;">
		<!-- BEGIN CONTENT -->
		<div class="page-content-wrapper">
			<!-- BEGIN CONTENT BODY -->
			<div class="page-content">

				<div class="main">
					<div class="body container">
						<div>
							<h2>撰写新文章</h2>
						</div>
						<div class="row typecho-page-main typecho-post-area" role="form">
							<form action="${ctx }/admin/article/edit-post" method="post" name="write_post">
								<div class="col-mb-12 col-tb-9" role="main">

									<p class="title">
										<label for="title" class="sr-only">标题</label> <input
											type="text" id="title" name="title" autocomplete="off"
											value="" placeholder="标题" class="w-100 text title" />
									</p>
									<p>
										<label for="text" class="sr-only">文章内容</label>
										<textarea style="height: ${editorSize}px" autocomplete="off" id="text"
											name="text" class="w-100 mono"></textarea>
									</p>
									<section id="custom-field" class="typecho-post-option fold">
										<label id="custom-field-expand" class="typecho-label"><a
											href="##"><i class="i-caret-right"></i> 自定义字段</a></label>
										<table class="typecho-list-table mono">
											<colgroup>
												<col width="25%" />
												<col width="10%" />
												<col width="55%" />
												<col width="10%" />
											</colgroup>
											<tr>
												<td><label for="fieldname" class="sr-only">字段名称</label>
													<input type="text" name="fieldNames[]" placeholder="字段名称"
													id="fieldname" class="text-s w-100"></td>
												<td><label for="fieldtype" class="sr-only">字段类型</label>
													<select name="fieldTypes[]" id="fieldtype">
														<option value="str">字符</option>
														<option value="int">整数</option>
														<option value="float">小数</option>
												</select></td>
												<td><label for="fieldvalue" class="sr-only">字段值</label>
													<textarea name="fieldValues[]" placeholder="字段值"
														id="fieldvalue" class="text-s w-100" rows="2"></textarea>
												</td>
												<td>
													<button type="button" class="btn btn-xs">删除</button>
												</td>
											</tr>
										</table>
										<div class="description clearfix">
											<button type="button" class="btn btn-xs operate-add">+添加字段</button>
											自定义字段可以扩展你的模板功能, 使用方法参见 <a
												href="http://docs.typecho.org/help/custom-fields">帮助文档</a>
										</div>
									</section>

									<p class="submit clearfix">
										<span class="right"> <input type="hidden" name="cid"
											value="" />
											<button type="submit" name="do" value="save" id="btn-save"
												class="btn">保存草稿</button>
											<button type="submit" name="do" value="publish"
												class="btn primary" id="btn-submit">发布文章</button> <input
											type="hidden" name="markdown" value="1" />
										</span>
									</p>

								</div>

								<div id="edit-secondary" class="col-mb-12 col-tb-3"
									role="complementary">
									<ul class="typecho-option-tabs clearfix">
										<li class="active w-50"><a href="#tab-advance">选项</a></li>
										<li class="w-50"><a href="#tab-files" id="tab-files-btn">附件</a></li>
									</ul>


									<div id="tab-advance" class="tab-content">
										<section class="typecho-post-option" role="application">
											<label for="date" class="typecho-label">发布日期</label>
											<p>
												<input class="typecho-date w-100" type="text" name="date"
													id="date" value="" />
											</p>
										</section>

										<section class="typecho-post-option category-option">
											<label class="typecho-label">分类</label>
											<ul>
												<c:forEach items="${category }" var="type">
												
												<li>
													<c:forEach   begin="1" end="${type.level }" step="1"  >
														&nbsp;&nbsp;&nbsp;
													</c:forEach>
												<input type="checkbox" id="category-${type.mid }" value="${type.mid }"
													name="category[${type.mid }]" /> <label for="category-${type.mid }">${type.name }</label></li>
												</c:forEach>
												 
											</ul>
										</section>

										<section class="typecho-post-option">
											<label for="token-input-tags" class="typecho-label">标签</label>
											<p>
												<input id="tags" name="tags" type="text" value=""
													class="w-100 text" />
											</p>
										</section>


										<button type="button" id="advance-panel-btn"
											class="btn btn-xs">
											高级选项 <i class="i-caret-down"></i>
										</button>
										<div id="advance-panel">
											<section class="typecho-post-option visibility-option">
												<label for="visibility" class="typecho-label">公开度</label>
												<p>
													<select id="visibility" name="visibility">
														<option value="publish" selected>公开</option>
														<option value="hidden">隐藏</option>
														<option value="password">密码保护</option>
														<option value="private">私密</option>
														<option value="waiting">待审核</option>
													</select>
												</p>
												<p id="post-password" class="hidden">
													<label for="protect-pwd" class="sr-only">内容密码</label> <input
														type="text" name="password" id="protect-pwd"
														class="text-s" value="" size="16" placeholder="内容密码" />
												</p>
											</section>

											<section class="typecho-post-option allow-option">
												<label class="typecho-label">权限控制</label>
												<ul>
													<li><input id="allowComment" name="allowcomment"
														type="checkbox" value="1" checked="true" /> <label
														for="allowComment">允许评论</label></li>
													<li><input id="allowPing" name="allowping"
														type="checkbox" value="1" checked="true" /> <label
														for="allowPing">允许被引用</label></li>
													<li><input id="allowFeed" name="allowfeed"
														type="checkbox" value="1" checked="true" /> <label
														for="allowFeed">允许在聚合中出现</label></li>
												</ul>
											</section>

											<section class="typecho-post-option">
												<label for="trackback" class="typecho-label">引用通告</label>
												<p>
													<textarea id="trackback" class="w-100 mono"
														name="trackback" rows="2"></textarea>
												</p>
												<p class="description">每一行一个引用地址, 用回车隔开</p>
											</section>

										</div>
										<!-- end #advance-panel -->

									</div>
									<!-- end #tab-advance -->

									<div id="tab-files" class="tab-content hidden">


										<div id="upload-panel" class="p">
											<div class="upload-area" draggable="true">
												拖放文件到这里<br>或者 <a href="###" class="upload-file">选择文件上传</a>
											</div>
											<ul id="file-list">
											</ul>
										</div>

									</div>
									<!-- end #tab-files -->
								</div>
							</form>
						</div>
					</div>
				</div>













			</div>
			<!-- END CONTENT BODY -->
		</div>
		<!-- END CONTENT -->

	</div>
	<!-- END CONTAINER -->

	<!--[if lt IE 9]>
<script src="${ctx}/resources/assets/global/plugins/respond.min.js"></script>
<script src="${ctx}/resources/assets/global/plugins/excanvas.min.js"></script> 
<![endif]-->
	<!-- BEGIN CORE PLUGINS -->
	<script src="${ctx}/resources/assets/global/plugins/jquery.min.js"
		type="text/javascript"></script>
 
	<!-- END PAGE LEVEL PLUGINS -->



	<!-- BEGIN THEME LAYOUT SCRIPTS -->

	<script type="text/javascript">
	    function checkSubmit(){
	    	var sHTML = $('#summernote_1').summernote('code');
	    	$('#content').val(sHTML);
	    	return true;
	    }
		$(function() {

		});
	</script>
	<!-- END THEME LAYOUT SCRIPTS -->
	<script src="${ctx}/resources/blog/js/jquery.js"></script>
	<script src="${ctx}/resources/blog/js/jquery-ui.js"></script>
	<script src="${ctx}/resources/blog/js/typecho.js"></script>
	 
	<script>
(function () {
    $(document).ready(function () {
        var error = $('.typecho-option .error:first');

        if (error.length > 0) {
            $('html,body').scrollTop(error.parents('.typecho-option').offset().top);
        }

        $('form').submit(function () {
            if (this.submitted) {
                return false;
            } else {
                this.submitted = true;
            }
        });

        $('label input[type=text]').click(function (e) {
            var check = $('#' + $(this).parents('label').attr('for'));
            check.prop('checked', true);
            return false;
        });
    });
})();
</script>

	<script src="${ctx}/resources/blog/js/timepicker.js"></script>
	<script src="${ctx}/resources/blog/js/tokeninput.js"></script>
	<script>
$(document).ready(function() {
    // 日期时间控件
    $('#date').mask('9999-99-99 99:99').datetimepicker({
        currentText     :   '现在',
        prevText        :   '上一月',
        nextText        :   '下一月',
        monthNames      :   ['一月', '二月', '三月', '四月',
            '五月', '六月', '七月', '八月',
            '九月', '十月', '十一月', '十二月'],
        dayNames        :   ['星期日', '星期一', '星期二',
            '星期三', '星期四', '星期五', '星期六'],
        dayNamesShort   :   ['周日', '周一', '周二', '周三',
            '周四', '周五', '周六'],
        dayNamesMin     :   ['日', '一', '二', '三',
            '四', '五', '六'],
        closeText       :   '完成',
        timeOnlyTitle   :   '选择时间',
        timeText        :   '时间',
        hourText        :   '时',
        amNames         :   ['上午', 'A'],
        pmNames         :   ['下午', 'P'],
        minuteText      :   '分',
        secondText      :   '秒',

        dateFormat      :   'yy-mm-dd',
        hour            :   (new Date()).getHours(),
        minute          :   (new Date()).getMinutes()
    });

    // 聚焦
    $('#title').select();

    // text 自动拉伸
    Typecho.editorResize('text', '${ctx}/admin/blog/options/editorSize');

    // tag autocomplete 提示
    var tags = $('#tags'), tagsPre = [];
    
    if (tags.length > 0) {
        var items = tags.val().split(','), result = [];
        for (var i = 0; i < items.length; i ++) {
            var tag = items[i];

            if (!tag) {
                continue;
            }

            tagsPre.push({
                id      :   tag,
                tags    :   tag
            });
        }

        tags.tokenInput([], {
            propertyToSearch:   'tags',
            tokenValue      :   'tags',
            searchDelay     :   0,
            preventDuplicates   :   true,
            animateDropdown :   false,
            hintText        :   '请输入标签名',
            noResultsText   :   '此标签不存在, 按回车创建',
            prePopulate     :   tagsPre,

            onResult        :   function (result, query) {
                if (!query) {
                    return result;
                }

                if (!result) {
                    result = [];
                }

                if (!result[0] || result[0]['id'] != query) {
                    result.unshift({
                        id      :   query,
                        tags    :   query
                    });
                }

                return result.slice(0, 5);
            }
        });

        // tag autocomplete 提示宽度设置
        $('#token-input-tags').focus(function() {
            var t = $('.token-input-dropdown'),
                offset = t.outerWidth() - t.width();
            t.width($('.token-input-list').outerWidth() - offset);
        });
    }

    // 缩略名自适应宽度
    var slug = $('#slug');

    if (slug.length > 0) {
        var wrap = $('<div />').css({
            'position'  :   'relative',
            'display'   :   'inline-block'
        }),
        justifySlug = $('<pre />').css({
            'display'   :   'block',
            'visibility':   'hidden',
            'height'    :   slug.height(),
            'padding'   :   '0 2px',
            'margin'    :   0
        }).insertAfter(slug.wrap(wrap).css({
            'left'      :   0,
            'top'       :   0,
            'minWidth'  :   '5px',
            'position'  :   'absolute',
            'width'     :   '100%'
        })), originalWidth = slug.width();

        function justifySlugWidth() {
            var val = slug.val();
            justifySlug.text(val.length > 0 ? val : '     ');
        }

        slug.bind('input propertychange', justifySlugWidth);
        justifySlugWidth();
    }

    // 原始的插入图片和文件
    Typecho.insertFileToEditor = function (file, url, isImage) {
        var textarea = $('#text'), sel = textarea.getSelection(),
            html = isImage ? '<img src="' + url + '" alt="' + file + '" />'
                : '<a href="' + url + '">' + file + '</a>',
            offset = (sel ? sel.start : 0) + html.length;

        textarea.replaceSelection(html);
        textarea.setSelection(offset, offset);
    };

    var submitted = false, form = $('form[name=write_post],form[name=write_page]').submit(function () {
        submitted = true;
    }), savedData = null;

    // 自动保存

    // 自动检测离开页
    var lastData = form.serialize();

    $(window).bind('beforeunload', function () {
        if (!!savedData) {
            lastData = savedData;
        }

        if (form.serialize() != lastData && !submitted) {
            return '内容已经改变尚未保存, 您确认要离开此页面吗?';
        }
    });

    // 控制选项和附件的切换
    var fileUploadInit = false;
    $('#edit-secondary .typecho-option-tabs li').click(function() {
        $('#edit-secondary .typecho-option-tabs li').removeClass('active');
        $(this).addClass('active');
        $('.tab-content').addClass('hidden');
        
        var selected_tab = $(this).find('a').attr('href'),
            selected_el = $(selected_tab).removeClass('hidden');

        if (!fileUploadInit) {
            selected_el.trigger('init');
            fileUploadInit = true;
        }

        return false;
    });

    // 高级选项控制
    $('#advance-panel-btn').click(function() {
        $('#advance-panel').toggle();
        return false;
    });

    // 自动隐藏密码框
    $('#visibility').change(function () {
        var val = $(this).val(), password = $('#post-password');

        if ('password' == val) {
            password.removeClass('hidden');
        } else {
            password.addClass('hidden');
        }
    });
    
    // 草稿删除确认
    $('.edit-draft-notice a').click(function () {
        if (confirm('您确认要删除这份草稿吗?')) {
            window.location.href = $(this).attr('href');
        }

        return false;
    });
});
</script>

	<script src="${ctx}/resources/blog/js/pagedown.js"></script>
	<script src="${ctx}/resources/blog/js/stmd.js"></script>
	<script src="${ctx}/resources/blog/js/diff.js"></script>
	<script>
$(document).ready(function () {
    var textarea = $('#text'),
        toolbar = $('<div class="editor" id="wmd-button-bar" />').insertBefore(textarea.parent()),
        preview = $('<div id="wmd-preview" class="wmd-hidetab" />').insertAfter('.editor');

    var options = {}, isMarkdown = 1;

    options.strings = {
        bold: '加粗 <strong> Ctrl+B',
        boldexample: '加粗文字',
            
        italic: '斜体 <em> Ctrl+I',
        italicexample: '斜体文字',

        link: '链接 <a> Ctrl+L',
        linkdescription: '请输入链接描述',

        quote:  '引用 <blockquote> Ctrl+Q',
        quoteexample: '引用文字',

        code: '代码 <pre><code> Ctrl+K',
        codeexample: '请输入代码',

        image: '图片 <img> Ctrl+G',
        imagedescription: '请输入图片描述',

        olist: '数字列表 <ol> Ctrl+O',
        ulist: '普通列表 <ul> Ctrl+U',
        litem: '列表项目',

        heading: '标题 <h1>/<h2> Ctrl+H',
        headingexample: '标题文字',

        hr: '分割线 <hr> Ctrl+R',
        more: '摘要分割线 <!--more--> Ctrl+M',

        undo: '撤销 - Ctrl+Z',
        redo: '重做 - Ctrl+Y',
        redomac: '重做 - Ctrl+Shift+Z',

        fullscreen: '全屏 - Ctrl+J',
        exitFullscreen: '退出全屏 - Ctrl+E',
        fullscreenUnsupport: '此浏览器不支持全屏操作',

        imagedialog: '<p><b>插入图片</b></p><p>请在下方的输入框内输入要插入的远程图片地址</p><p>您也可以使用附件功能插入上传的本地图片</p>',
        linkdialog: '<p><b>插入链接</b></p><p>请在下方的输入框内输入要插入的链接地址</p>',

        ok: '确定',
        cancel: '取消',

        help: 'Markdown语法帮助'
    };

    var converter = new Typecho.Markdown,
        editor = new Markdown.Editor(converter, '', options),
        diffMatch = new diff_match_patch(), last = '', preview = $('#wmd-preview'),
        mark = '@mark' + Math.ceil(Math.random() * 100000000) + '@',
        span = '<span class="diff" />',
        cache = {};
    

    // 自动跟随
    converter.hooks.chain('postConversion', function (html) {
        // clear special html tags
        html = html.replace(/<\/?(\!doctype|html|head|body|link|title|input|select|button|textarea|style|noscript)[^>]*>/ig, function (all) {
            return all.replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/'/g, '&#039;')
                .replace(/"/g, '&quot;');
        });

        // clear hard breaks
        html = html.replace(/\s*((?:<br>\n)+)\s*(<\/?(?:p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|li|dd|dt)[^\w])/gm, '$2');

        if (html.indexOf('<!--more-->') > 0) {
            var parts = html.split(/\s*<\!\-\-more\-\->\s*/),
                summary = parts.shift(),
                details = parts.join('');

            html = '<div class="summary">' + summary + '</div>'
                + '<div class="details">' + details + '</div>';
        }


        var diffs = diffMatch.diff_main(last, html);
        last = html;

        if (diffs.length > 0) {
            var stack = [], markStr = mark;
            
            for (var i = 0; i < diffs.length; i ++) {
                var diff = diffs[i], op = diff[0], str = diff[1]
                    sp = str.lastIndexOf('<'), ep = str.lastIndexOf('>');

                if (op != 0) {
                    if (sp >=0 && sp > ep) {
                        if (op > 0) {
                            stack.push(str.substring(0, sp) + markStr + str.substring(sp));
                        } else {
                            var lastStr = stack[stack.length - 1], lastSp = lastStr.lastIndexOf('<');
                            stack[stack.length - 1] = lastStr.substring(0, lastSp) + markStr + lastStr.substring(lastSp);
                        }
                    } else {
                        if (op > 0) {
                            stack.push(str + markStr);
                        } else {
                            stack.push(markStr);
                        }
                    }
                    
                    markStr = '';
                } else {
                    stack.push(str);
                }
            }

            html = stack.join('');

            if (!markStr) {
                var pos = html.indexOf(mark), prev = html.substring(0, pos),
                    next = html.substr(pos + mark.length),
                    sp = prev.lastIndexOf('<'), ep = prev.lastIndexOf('>');

                if (sp >= 0 && sp > ep) {
                    html = prev.substring(0, sp) + span + prev.substring(sp) + next;
                } else {
                    html = prev + span + next;
                }
            }
        }

        // 替换img
        html = html.replace(/<(img)\s+([^>]*)\s*src="([^"]+)"([^>]*)>/ig, function (all, tag, prefix, src, suffix) {
            if (!cache[src]) {
                cache[src] = false;
            } else {
                return '<span class="cache" data-width="' + cache[src][0] + '" data-height="' + cache[src][1] + '" '
                    + 'style="background:url(' + src + ') no-repeat left top; width:'
                    + cache[src][0] + 'px; height:' + cache[src][1] + 'px; display: inline-block; max-width: 100%;'
                    + '-webkit-background-size: contain;-moz-background-size: contain;-o-background-size: contain;background-size: contain;" />';
            }

            return all;
        });

        // 替换block
        html = html.replace(/<(iframe|embed)\s+([^>]*)>/ig, function (all, tag, src) {
            if (src[src.length - 1] == '/') {
                src = src.substring(0, src.length - 1);
            }

            return '<div style="background: #ddd; height: 40px; overflow: hidden; line-height: 40px; text-align: center; font-size: 12px; color: #777">'
                + tag + ' : ' + $.trim(src) + '</div>';
        });

        return html;
    });

    function cacheResize() {
        var t = $(this), w = parseInt(t.data('width')), h = parseInt(t.data('height')),
            ow = t.width();

        t.height(h * ow / w);
    }

    var to;
    editor.hooks.chain('onPreviewRefresh', function () {
        var diff = $('.diff', preview), scrolled = false;

        if (to) {
            clearTimeout(to);
        }

        $('img', preview).load(function () {
            var t = $(this), src = t.attr('src');

            if (scrolled) {
                preview.scrollTo(diff, {
                    offset  :   - 50
                });
            }

            if (!!src && !cache[src]) {
                cache[src] = [this.width, this.height];
            }
        });

        $('.cache', preview).resize(cacheResize).each(cacheResize);
        
        var changed = $('.diff', preview).parent();
        if (!changed.is(preview)) {
            changed.css('background-color', 'rgba(255,230,0,0.5)');
            to = setTimeout(function () {
                changed.css('background-color', 'transparent');
            }, 4500);
        }

        if (diff.length > 0) {
            var p = diff.position(), lh = diff.parent().css('line-height');
            lh = !!lh ? parseInt(lh) : 0;

            if (p.top < 0 || p.top > preview.height() - lh) {
                preview.scrollTo(diff, {offset: - 50 });
                scrolled = true;
            }
        }
    });

    
    var input = $('#text'), th = textarea.height(), ph = preview.height(),
        uploadBtn = $('<button type="button" id="btn-fullscreen-upload" class="btn btn-link">'
            + '<i class="i-upload">附件</i></button>')
            .prependTo('.submit .right')
            .click(function() {
                $('a', $('.typecho-option-tabs li').not('.active')).trigger('click');
                return false;
            });

    $('.typecho-option-tabs li').click(function () {
        uploadBtn.find('i').toggleClass('i-upload-active',
            $('#tab-files-btn', this).length > 0);
    });

    editor.hooks.chain('enterFakeFullScreen', function () {
        th = textarea.height();
        ph = preview.height();
        $(document.body).addClass('fullscreen');
        var h = $(window).height() - toolbar.outerHeight();
        
        textarea.css('height', h);
        preview.css('height', h);
    });

    editor.hooks.chain('enterFullScreen', function () {
        $(document.body).addClass('fullscreen');
        
        var h = window.screen.height - toolbar.outerHeight();
        textarea.css('height', h);
        preview.css('height', h);
    });

    editor.hooks.chain('exitFullScreen', function () {
        $(document.body).removeClass('fullscreen');
        textarea.height(th);
        preview.height(ph);
    });

    function initMarkdown() {
        editor.run();

        var imageButton = $('#wmd-image-button'),
            linkButton = $('#wmd-link-button');

        Typecho.insertFileToEditor = function (file, url, isImage) {
            var button = isImage ? imageButton : linkButton;

            options.strings[isImage ? 'imagename' : 'linkname'] = file;
            button.trigger('click');

            var checkDialog = setInterval(function () {
                if ($('.wmd-prompt-dialog').length > 0) {
                    $('.wmd-prompt-dialog input').val(url).select();
                    clearInterval(checkDialog);
                    checkDialog = null;
                }
            }, 10);
        };

        Typecho.uploadComplete = function (file) {
            Typecho.insertFileToEditor(file.title, file.url, file.isImage);
        };

        // 编辑预览切换
        var edittab = $('.editor').prepend('<div class="wmd-edittab"><a href="#wmd-editarea" class="active">撰写</a><a href="#wmd-preview">预览</a></div>'),
            editarea = $(textarea.parent()).attr("id", "wmd-editarea");

        $(".wmd-edittab a").click(function() {
            $(".wmd-edittab a").removeClass('active');
            $(this).addClass("active");
            $("#wmd-editarea, #wmd-preview").addClass("wmd-hidetab");
        
            var selected_tab = $(this).attr("href"),
                selected_el = $(selected_tab).removeClass("wmd-hidetab");

            // 预览时隐藏编辑器按钮
            if (selected_tab == "#wmd-preview") {
                $("#wmd-button-row").addClass("wmd-visualhide");
            } else {
                $("#wmd-button-row").removeClass("wmd-visualhide");
            }

            // 预览和编辑窗口高度一致
            $("#wmd-preview").outerHeight($("#wmd-editarea").innerHeight());

            return false;
        });
    }

    if (isMarkdown) {
        initMarkdown();
    } else {
        var notice = $('<div class="message notice">这篇文章不是由Markdown语法创建的, 继续使用Markdown编辑它吗? '
            + '<button class="btn btn-xs primary yes">是</button> ' 
            + '<button class="btn btn-xs no">否</button></div>')
            .hide().insertBefore(textarea).slideDown();

        $('.yes', notice).click(function () {
            notice.remove();
            $('<input type="hidden" name="markdown" value="1" />').appendTo('.submit');
            initMarkdown();
        });

        $('.no', notice).click(function () {
            notice.remove();
        });
    }
});
</script>


	<script src="${ctx}/resources/blog/js/moxie.js"></script>
	<script src="${ctx}/resources/blog/js/plupload.js"></script>
	<script>
$(document).ready(function() {
    function updateAttacmentNumber () {
        var btn = $('#tab-files-btn'),
            balloon = $('.balloon', btn),
            count = $('#file-list li .insert').length;

        if (count > 0) {
            if (!balloon.length) {
                btn.html($.trim(btn.html()) + ' ');
                balloon = $('<span class="balloon"></span>').appendTo(btn);
            }

            balloon.html(count);
        } else if (0 == count && balloon.length > 0) {
            balloon.remove();
        }
    }

    $('.upload-area').bind({
        dragenter   :   function () {
            $(this).parent().addClass('drag');
        },

        dragover    :   function (e) {
            $(this).parent().addClass('drag');
        },

        drop        :   function () {
            $(this).parent().removeClass('drag');
        },
        
        dragend     :   function () {
            $(this).parent().removeClass('drag');
        },

        dragleave   :   function () {
            $(this).parent().removeClass('drag');
        }
    });

    updateAttacmentNumber();

    function fileUploadStart (file) {
        $('<li id="' + file.id + '" class="loading">'
            + file.name + '</li>').appendTo('#file-list');
    }

    function fileUploadError (error) {
        var file = error.file, code = error.code, word; 
        
        switch (code) {
            case plupload.FILE_SIZE_ERROR:
                word = '文件大小超过限制';
                break;
            case plupload.FILE_EXTENSION_ERROR:
                word = '文件扩展名不被支持';
                break;
            case plupload.FILE_DUPLICATE_ERROR:
                word = '文件已经上传过';
                break;
            case plupload.HTTP_ERROR:
            default:
                word = '上传出现错误';
                break;
        }

        var fileError = '%s 上传失败'.replace('%s', file.name),
            li, exist = $('#' + file.id);

        if (exist.length > 0) {
            li = exist.removeClass('loading').html(fileError);
        } else {
            li = $('<li>' + fileError + '<br />' + word + '</li>').appendTo('#file-list');
        }

        li.effect('highlight', {color : '#FBC2C4'}, 2000, function () {
            $(this).remove();
        });
    }

    var completeFile = null;
    function fileUploadComplete (id, url, data) {
        var li = $('#' + id).removeClass('loading').data('cid', data.cid)
            .data('url', data.url)
            .data('image', data.isImage)
            .html('<input type="hidden" name="attachment[]" value="' + data.cid + '" />'
                + '<a class="insert" target="_blank" href="###" title="点击插入文件">' + data.title + '</a><div class="info">' + data.bytes
                + ' <a class="file" target="_blank" href="${ctx}/resources/blog/media.php?cid=' 
                + data.cid + '" title="编辑"><i class="i-edit"></i></a>'
                + ' <a class="delete" href="###" title="删除"><i class="i-delete"></i></a></div>')
            .effect('highlight', 1000);
            
        attachInsertEvent(li);
        attachDeleteEvent(li);
        updateAttacmentNumber();

        if (!completeFile) {
            completeFile = data;
        }
    }

    $('#tab-files').bind('init', function () {
        var uploader = new plupload.Uploader({
            browse_button   :   $('.upload-file').get(0),
            url             :   'http://192.168.233.131/blog/index.php/action/upload?_=c65fd67d7976bf2d97d08e2689d9a39b',
            runtimes        :   'html5,flash,html4',
            flash_swf_url   :   '${ctx}/resources/blog/js/Moxie.swf',
            drop_element    :   $('.upload-area').get(0),
            filters         :   {
                max_file_size       :   '2mb',
                mime_types          :   [{'title' : '允许上传的文件', 'extensions' : 'gif,jpg,jpeg,png,tiff,bmp'}],
                prevent_duplicates  :   true
            },

            init            :   {
                FilesAdded      :   function (up, files) {
                    plupload.each(files, function(file) {
                        fileUploadStart(file);
                    });

                    completeFile = null;
                    uploader.start();
                },

                UploadComplete  :   function () {
                    if (completeFile) {
                        Typecho.uploadComplete(completeFile);
                    }
                },

                FileUploaded    :   function (up, file, result) {
                    if (200 == result.status) {
                        var data = $.parseJSON(result.response);

                        if (data) {
                            fileUploadComplete(file.id, data[0], data[1]);
                            return;
                        }
                    }

                    fileUploadError({
                        code : plupload.HTTP_ERROR,
                        file : file
                    });
                },

                Error           :   function (up, error) {
                    fileUploadError(error);
                }
            }
        });

        uploader.init();
    });

    function attachInsertEvent (el) {
        $('.insert', el).click(function () {
            var t = $(this), p = t.parents('li');
            Typecho.insertFileToEditor(t.text(), p.data('url'), p.data('image'));
            return false;
        });
    }

    function attachDeleteEvent (el) {
        var file = $('a.insert', el).text();
        $('.delete', el).click(function () {
            if (confirm('确认要删除文件 %s 吗?'.replace('%s', file))) {
                var cid = $(this).parents('li').data('cid');
                $.post('http://192.168.233.131/blog/index.php/action/contents-attachment-edit?_=c65fd67d7976bf2d97d08e2689d9a39b',
                    {'do' : 'delete', 'cid' : cid},
                    function () {
                        $(el).fadeOut(function () {
                            $(this).remove();
                            updateAttacmentNumber();
                        });
                    });
            }

            return false;
        });
    }

    $('#file-list li').each(function () {
        attachInsertEvent(this);
        attachDeleteEvent(this);
    });
});
</script>

	<script>
$(document).ready(function () {
    // 自定义字段
    $('#custom-field-expand').click(function() {
        var btn = $('i', this);
        if (btn.hasClass('i-caret-right')) {
            btn.removeClass('i-caret-right').addClass('i-caret-down');
        } else {
            btn.removeClass('i-caret-down').addClass('i-caret-right');
        }
        $(this).parent().toggleClass('fold');
        return false;
    });

    function attachDeleteEvent (el) {
        $('button.btn-xs', el).click(function () {
            if (confirm('确认要删除此字段吗?')) {
                $(this).parents('tr').fadeOut(function () {
                    $(this).remove();
                });
            }
        });
    }

    $('#custom-field table tbody tr').each(function () {
        attachDeleteEvent(this);
    });

    $('#custom-field button.operate-add').click(function () {
        var html = '<tr><td><input type="text" name="fieldNames[]" placeholder="字段名称" class="text-s w-100"></td>'
                + '<td><select name="fieldTypes[]" id="">'
                + '<option value="str">字符</option>'
                + '<option value="int">整数</option>'
                + '<option value="float">小数</option>'
                + '</select></td>'
                + '<td><textarea name="fieldValues[]" placeholder="字段值" class="text-s w-100" rows="2"></textarea></td>'
                + '<td><button type="button" class="btn btn-xs">删除</button></td></tr>',
            el = $(html).hide().appendTo('#custom-field table tbody').fadeIn();

        attachDeleteEvent(el);
    });
});
</script>
</body>
</html>